package com.wangsd.web.service.impl;

import com.wangsd.core.entity.JSONResult;
import com.wangsd.core.feature.orm.mybatis.Page;
import com.wangsd.core.util.AccuracyCalculation;
import com.wangsd.core.util.DateUtils;
import com.wangsd.core.util.ExcelModelStyleUtil;
import com.wangsd.core.util.StaticVar;
import com.wangsd.web.dao.BillaccountMapper;
import com.wangsd.web.dao.TicketMapper;
import com.wangsd.web.model.*;
import com.wangsd.web.modelCustom.BillAccountCustom;
import com.wangsd.web.modelCustom.BillExcelBean;
import com.wangsd.web.service.BillAccountService;
import com.wangsd.web.service.HousinginfoService;
import com.wangsd.web.service.RoominfoService;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2017/11/16.
 */
@Service
public class BillAccountServiceImpl implements BillAccountService {

    @Autowired
    BillaccountMapper billaccountMapper;
    @Autowired
    TicketMapper ticketMapper;
    @Autowired
    RoominfoService roominfoService;
    @Autowired
    HousinginfoService housinginfoService;


    @Override
    public List<BillAccountCustom> queryBillAccountList(BillAccountCustom billAccountCustom) {
        List<BillAccountCustom> billAccountCustoms = billaccountMapper.queryBillAccountList(billAccountCustom);
        String accountSum = billaccountMapper.queryBillAccountSum(billAccountCustom);
        if (billAccountCustoms != null && billAccountCustoms.size() > 0) {
            billAccountCustoms.get(billAccountCustoms.size()-1).setAccountSum(accountSum);
        }
        return billAccountCustoms;
    }

    @Override
    public Billaccount selectBillAccountById(Integer id) {
        return billaccountMapper.selectByPrimaryKey(id);
    }

    @Override
    public Billaccount selectBillAccountByTradeNo(String tradeNo) {
        BillaccountExample example = new BillaccountExample();
        example.createCriteria().andAlipayTradeNoEqualTo(tradeNo);
        List<Billaccount> list = billaccountMapper.selectByExample(example);
        if (list.size() > 0) {
            return list.get(0);
        } else {
            return null;
        }
    }

    /**
     * 新增账单信息
     *
     * @param billaccount
     * @return
     */
    @Override
    public boolean insertBillaccount(Billaccount billaccount) {
        int ret = billaccountMapper.insertSelective(billaccount);
        if (ret > 0) {
            return true;
        } else {
            return true;
        }
    }

    /**
     * 更新账单信息
     *
     * @param billaccount
     * @return
     */
    @Override
    public boolean updateBillaccount(Billaccount billaccount) {
        int ret = billaccountMapper.updateByPrimaryKeySelective(billaccount);
        if (ret > 0) {
            return true;
        } else {
            return true;
        }
    }

    @Override
    public boolean deleteBillaccount(Integer id) {
        Billaccount billaccount = new Billaccount();
        billaccount.setId(id);
        billaccount.setDeletestatus(true);
        int ret = billaccountMapper.updateByPrimaryKeySelective(billaccount);
        if (ret > 0) {
            return true;
        } else {
            return true;
        }
    }

    @Override
    public JSONResult importBillaccount(List<BillExcelBean> list, Integer costType) {
        JSONResult jsonResult = new JSONResult();
        jsonResult.setMessage("开始导入。");
        int count = 0;
        BigDecimal sumAccount = new BigDecimal(0);
        BigDecimal result = new BigDecimal(0);

        Housinginfo housinginfo = housinginfoService.selectHousingByName(list.get(0).getHousingName());
        if (housinginfo != null) {
            //处理数据
            int i = 2;
            for (BillExcelBean bean : list) {
                Roominfo roominfo = new Roominfo();
                roominfo.setParentId(housinginfo.getId());
                roominfo.setGroupName(bean.getGroupName());
                roominfo.setBuilding(bean.getBuildName());
                roominfo.setUnit(bean.getUnitName());
                roominfo.setRoom(bean.getRoomName());
                Roominfo old = roominfoService.selectRoominfoByContent(roominfo);
                if (old == null) {
                    jsonResult.setMessage(jsonResult.getMessage() + "第" + i + "行，房屋信息不存在。");
                } else {
                    BillAccountCustom billaccount = new BillAccountCustom();
                    billaccount.setHousingId(housinginfo.getId());
                    billaccount.setRoominfoId(old.getId());
                    billaccount.setBillEntryAmount(bean.getAmountName());
                    billaccount.setAcctPeriod(bean.getAcctName());
                    billaccount.setCostType(costType);
                    List<BillAccountCustom> bi = queryBillAccountList(billaccount);
                    if (bi.size() > 0) {
                        jsonResult.setMessage(jsonResult.getMessage() + "。第" + i + "行，账单信息已存在。");
                        continue;
                    } else {
                        count++;
                        sumAccount = sumAccount.add(new BigDecimal(bean.getAmountName()));
                        result = sumAccount.setScale(2, BigDecimal.ROUND_HALF_UP);
                        billaccount.setReleaseDay(bean.getReleaseName());
                        billaccount.setDeadline(bean.getDeadlineName());
                        billaccount.setCreateTime(new Date());
                        insertBillaccount(billaccount);
                    }
                }
                i++;
            }
        } else {
            jsonResult.setSuccess(false);
            jsonResult.setMessage("小区不存在。");
            return jsonResult;
        }
        jsonResult.setMessage(jsonResult.getMessage() + "导入" + count + "条,总金额:" + result);
        jsonResult.setSuccess(true);
        return jsonResult;
    }

    @Override
    public List<BillAccountCustom> queryAmountGroupByPayType(BillAccountCustom billAccountCustom) {
        return billaccountMapper.queryAmountGroupByPayType(billAccountCustom);
    }

    @Override
    public List<BillAccountCustom> queryCountGroupByPayType(BillAccountCustom billAccountCustom) {
        return billaccountMapper.queryCountGroupByPayType(billAccountCustom);
    }

    @Override
    public BillAccountCustom selectAllGroupByStatus(BillAccountCustom billAccountCustom) {
        return billaccountMapper.selectAllGroupByStatus(billAccountCustom);
    }

    /**
     * 新增电子发票信息
     *
     * @param ticket
     * @return
     */
    @Override
    public boolean insertTicket(Ticket ticket) {
        Billaccount billaccount = new Billaccount();
        billaccount.setId(ticket.getBillaccountId());
        billaccount.setTicketstatus(StaticVar.BILLACCOUNT_TICKETSTATUS1);
        this.updateBillaccount(billaccount);
        int ret = ticketMapper.insertSelective(ticket);
        if (ret > 0) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 根据主键查询电子发票
     *
     * @return
     */
    @Override
    public Ticket selectTicketById(Integer id) {
        return ticketMapper.selectByPrimaryKey(id);
    }


    public List<BillAccountCustom> queryInvoiceListTicketstatus(Page<BillAccountCustom> page, BillAccountCustom query) {
        return billaccountMapper.queryInvoiceListTicketstatus(page, query);
    }

    @Override
    public Integer queryBillAccountListAccount(BillAccountCustom billAccountCustom) {
        return billaccountMapper.queryBillAccountListAccount(billAccountCustom);
    }

    @Override
    public BillAccountCustom queryAmountGroup(BillAccountCustom billAccountCustom) {
        return billaccountMapper.queryAmountGroup(billAccountCustom);
    }

    public HSSFWorkbook exportBillAccount(BillAccountCustom billAccountCustom) {
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet();
        ExcelModelStyleUtil.setTitleCellStyles(workbook, sheet);
        List<BillAccountCustom> list1 = billaccountMapper.queryBillAccountList(billAccountCustom);
        List<String[]> list2 = new ArrayList<String[]>();
        list2.add(new String[]{"序号", "小区名称", "完整门牌", "账单编号",
                "业主名", "手机号", "费用类型", "账期", "金额",
                "付款类型", "发票流水号", "付款时间", "开票状态","税率","税额"});
        for (int i = 0; i < list1.size(); i++) {
            String housingName = list1.get(i).getHousingName();
            String roominfoAddress = list1.get(i).getRoominfoAddress();
            String id = String.valueOf(list1.get(i).getId());
            String ownerName = list1.get(i).getOwnerName();
            String ownerPhone = list1.get(i).getOwnerPhone();
            String costTypeName = list1.get(i).getCostTypeName();
            String acctPeriod = list1.get(i).getAcctPeriod();
            Double amount=list1.get(i).getBillEntryAmount();
            String billEntryAmount = String.valueOf(amount);
            int paytype = -1;
            if (list1.get(i).getPaytype() != null) {
                paytype = list1.get(i).getPaytype();
            }
            String paytypeName = "";
            if (paytype == 1) {
                paytypeName = "现金";
            } else if (paytype == 2) {
                paytypeName = "支付宝";
            } else if (paytype == 3) {
                paytypeName = "微信";
            } else if (paytype == 4) {
                paytypeName = "POS机";
            } else if (paytype == 5) {
                paytypeName = "银行转帐";
            } else if (paytype == 6) {
                paytypeName = "抵用券";
            } else if (paytype == 99) {
                paytypeName = "其他";
            }
            String invoiceserialnum = "";
            if (list1.get(i).getInvoiceserialnum() != null) {
                invoiceserialnum = list1.get(i).getInvoiceserialnum();
            }
            String paydate = "";
            if (list1.get(i).getPaydate() != null) {
                paydate = DateUtils.formatDatetime(list1.get(i).getPaydate());
            }
            int ticketstatus = -1;
            if (list1.get(i).getTicketstatus() != null) {
                ticketstatus = list1.get(i).getTicketstatus();
            }
            String ticketstatusName = "";
            if (ticketstatus == 0) {
                ticketstatusName = "未开票";
            } else if (ticketstatus == 1) {
                ticketstatusName = "已开票";
            } else if (ticketstatus == 2) {
                ticketstatusName = "退票";
            }
            String taxRate=list1.get(i).getTaxRate();
            Double taxRateNew=Double.valueOf(taxRate);
            Double amountNew=AccuracyCalculation.calculation(amount, taxRateNew);
            String amountNew1=String.valueOf(amountNew);
            list2.add(new String[]{String.valueOf(i + 1), housingName, roominfoAddress,
                    id, ownerName, ownerPhone, costTypeName, acctPeriod, billEntryAmount, paytypeName
                    , invoiceserialnum, paydate, ticketstatusName,taxRate,amountNew1});
        }
        for (int i = 0; i < list2.size(); i++) {
            HSSFRow row = sheet.createRow(i);
            String[] cells = list2.get(i);
            for (int j = 0; j < cells.length; j++) {
                String cellValue = cells[j];
                HSSFCell cell = row.createCell(j);
                cell.setCellValue(cellValue);
            }
        }
        return workbook;
    }

    public HSSFWorkbook exportBillAccountList(BillAccountCustom billAccountCustom) {
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet();
        ExcelModelStyleUtil.setTitleCellStylesNew(workbook, sheet);
        List<BillAccountCustom> list1 = billaccountMapper.queryBillAccountList(billAccountCustom);
        List<String[]> list2 = new ArrayList<String[]>();
        list2.add(new String[]{"序号", "小区名称", "完整门牌", "账单编号",
                "业主名", "费用类型", "账期", "应收金额",
                "付款类型", "付款状态", "支付宝付款编号", "付款时间", "创建时间", "同步状态", "打印状态", "备注"});
        for (int i = 0; i < list1.size(); i++) {
            String housingName = list1.get(i).getHousingName();
            String roominfoAddress = list1.get(i).getRoominfoAddress();
            String id = String.valueOf(list1.get(i).getId());
            String ownerName = list1.get(i).getOwnerName();
            String costTypeName = list1.get(i).getCostTypeName();
            String acctPeriod = list1.get(i).getAcctPeriod();
            String billEntryAmount = String.valueOf(list1.get(i).getBillEntryAmount());
            String remark = list1.get(i).getRemark() == null ? "" : list1.get(i).getRemark();
            int paytype = -1;
            if (list1.get(i).getPaytype() != null) {
                paytype = list1.get(i).getPaytype();
            }
            String paytypeName = "";
            if (paytype == 1) {
                paytypeName = "现金";
            } else if (paytype == 2) {
                paytypeName = "支付宝";
            } else if (paytype == 3) {
                paytypeName = "微信";
            } else if (paytype == 4) {
                paytypeName = "POS机";
            } else if (paytype == 5) {
                paytypeName = "银行转帐";
            } else if (paytype == 6) {
                paytypeName = "抵用券";
            } else if (paytype == 99) {
                paytypeName = "其他";
            }
            Boolean paystatus = false;
            if (list1.get(i).getPaystatus() != null) {
                paystatus = list1.get(i).getPaystatus();
            }
            String paystatusName = "";
            if (paystatus == true) {
                paystatusName = "已付款";
            } else {
                paystatusName = "未付款";
            }
            String alipayTradeNo = "";
            if (list1.get(i).getAlipayTradeNo() != null) {
                alipayTradeNo = list1.get(i).getAlipayTradeNo();
            }
            String paydate = "";
            if (list1.get(i).getPaydate() != null) {
                paydate = DateUtils.formatDatetime(list1.get(i).getPaydate());
            }
            String createTime = "";
            if (list1.get(i).getCreateTime() != null) {
                createTime = DateUtils.formatDatetime(list1.get(i).getCreateTime());
            }
            Boolean status = false;
            if (list1.get(i).getStatus() != null) {
                status = list1.get(i).getStatus();
            }
            String statusName = "";
            if (status == true) {
                statusName = "已同步";
            } else {
                statusName = "未同步";
            }

            Boolean printstatus = false;
            if (list1.get(i).getPrintstatus() != null) {
                printstatus = list1.get(i).getPrintstatus();
            }
            String printstatusName = "";
            if (printstatus == true) {
                printstatusName = "已打印";
            } else {
                printstatusName = "未打印";
            }
            list2.add(new String[]{String.valueOf(i + 1), housingName, roominfoAddress,
                    id, ownerName, costTypeName, acctPeriod, billEntryAmount, paytypeName, paystatusName
                    , alipayTradeNo, paydate, createTime, statusName, printstatusName, remark});
        }
        for (int i = 0; i < list2.size(); i++) {
            HSSFRow row = sheet.createRow(i);
            String[] cells = list2.get(i);
            for (int j = 0; j < cells.length; j++) {
                String cellValue = cells[j];
                HSSFCell cell = row.createCell(j);
                cell.setCellValue(cellValue);
            }
        }
        return workbook;
    }

    @Override
    public List<BillAccountCustom> getTradeCenterList(BillAccountCustom billAccountCustom) {
        return billaccountMapper.getTradeCenterList(billAccountCustom);
    }

    @Override
    public int updateByPrimaryKeySelective(Billaccount record) {
        return billaccountMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public BillAccountCustom selectBillAccountAndCostTypeById(Integer id) {
        return billaccountMapper.selectBillAccountAndCostTypeById(id);
    }

    @Override
    public List<BillAccountCustom> tableWorkReport(BillAccountCustom billAccountCustom) {
        return billaccountMapper.tableWorkReport(billAccountCustom);
    }

	@Override
	public List<Billaccount> selectBillAccountByInvoiceserialnum(String invoiceserialnum) {
		BillaccountExample example=new BillaccountExample();
		example.createCriteria().andInvoiceserialnumEqualTo(invoiceserialnum);
		List<Billaccount> list=billaccountMapper.selectByExample(example);
		return list;
	}

    @Override
    public List<BillAccountCustom> billAccountAcct(BillAccountCustom billAccountCustom) {
        return billaccountMapper.billAccountAcct(billAccountCustom);
    }
}
